package org.example.Polls;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TextView;
import android.widget.Toast;

public class ViewPollsActivity extends TabActivity implements OnTabChangeListener {
	private static final String MYPOLLS_TAB_TAG = "myPolls";
	private static final String PARTICIPATINGPOLLS_TAB_TAG = "participatingPolls";
	private static final String PUBLICPOLLS_TAB_TAG = "publicPolls";
	
	private ListView myPollsListView;
	private ListView participatingPollsListView;
	private ListView publicPollsListView;
	
	private TabHost mTabHost;
	
	private List<Poll> myPollsList = new ArrayList<Poll>();
	private List<Poll> participatingPollsList = new ArrayList<Poll>();
	private List<Poll> publicPollsList = new ArrayList<Poll>();
	
	private PollAdapter myPollsAdapter = new PollAdapter(this, myPollsList);
	private PollAdapter participatingPollsAdapter = new PollAdapter(this, participatingPollsList);
	private PollAdapter publicPollsAdapter = new PollAdapter(this, publicPollsList);
	
	private boolean initialized;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d("tag", "called onCreate" + " " + this);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_polls);
		
		mTabHost = getTabHost();
		mTabHost.setOnTabChangedListener(this);
		
		myPollsListView = (ListView) findViewById(R.id.view_polls_my_polls_list_view);
		participatingPollsListView = (ListView) findViewById(R.id.view_polls_participating_polls_list_view);
		publicPollsListView = (ListView) findViewById(R.id.view_polls_public_polls_list_view);
		
		myPollsListView.setAdapter(myPollsAdapter);
		participatingPollsListView.setAdapter(participatingPollsAdapter);
		publicPollsListView.setAdapter(publicPollsAdapter);
		
		myPollsListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View view, int position, long id) {
				Poll poll = (Poll) myPollsListView.getItemAtPosition(position);
				Long pollId = poll.getId();
				Intent intent = new Intent(getBaseContext(), ViewPollDetailsActivity.class); 
				intent.putExtra(ViewPollDetailsActivity.POLL_ID_EXTRA, pollId);
				startActivity(intent);
			}
		});
		
		participatingPollsListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View view, int position, long id) {
				Poll poll = (Poll) participatingPollsListView.getItemAtPosition(position);
				Long pollId = poll.getId();
				Intent intent = new Intent(getBaseContext(), ViewPollDetailsActivity.class); 
				intent.putExtra(ViewPollDetailsActivity.POLL_ID_EXTRA, pollId);
				startActivity(intent);
			}
		});
		
		publicPollsListView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView parent, View view, int position, long id) {
				Poll poll = (Poll) publicPollsListView.getItemAtPosition(position);
				Long pollId = poll.getId();
				Intent intent = new Intent(getBaseContext(), ViewPollDetailsActivity.class); 
				intent.putExtra(ViewPollDetailsActivity.POLL_ID_EXTRA, pollId);
				startActivity(intent);
			}
		});
		
		mTabHost.addTab(mTabHost.newTabSpec(MYPOLLS_TAB_TAG).setIndicator("My Polls").setContent(new TabContentFactory() {
			public View createTabContent(String arg0) {
				return myPollsListView;
			}
		}));
		mTabHost.addTab(mTabHost.newTabSpec(PARTICIPATINGPOLLS_TAB_TAG).setIndicator("Participating Polls").setContent(new TabContentFactory() {
			public View createTabContent(String arg0) {
				return participatingPollsListView;
			}
		}));
		mTabHost.addTab(mTabHost.newTabSpec(PUBLICPOLLS_TAB_TAG).setIndicator("Public Polls").setContent(new TabContentFactory() {
			public View createTabContent(String arg0) {
				return publicPollsListView;
			}
		}));
		
		registerForContextMenu(myPollsListView);
		registerForContextMenu(participatingPollsListView);
		registerForContextMenu(publicPollsListView);
		
		mTabHost.setCurrentTab(0);
		mTabHost.setCurrentTab(1);
		mTabHost.setCurrentTab(2);
		initialized = true;
		mTabHost.setCurrentTab(0);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Remove Poll?");
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.poll_details_or_remove_menu, menu);
	}
	
	// If I remove one item, it removes all the items!!!  :(
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		Intent intent;
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		switch(item.getItemId()) {
		case R.id.remove_item:
			switch(mTabHost.getCurrentTab()) {
			case 0:
				myPollsList.remove(info.position);
				myPollsAdapter.notifyDataSetChanged();
				break;
			case 1:
				participatingPollsList.remove(info.position);
				participatingPollsAdapter.notifyDataSetChanged();
				break;
			case 2:
				publicPollsList.remove(info.position);
				publicPollsAdapter.notifyDataSetChanged();
				break;
			}
			return true;
		case R.id.vote_for_item:
			switch(mTabHost.getCurrentTab()) {
			case 0:
				intent = new Intent(this, VoteOnPollActivity.class);
				Poll myPoll = (Poll) myPollsAdapter.getItem(info.position);
				intent.putExtra(VoteOnPollActivity.POLL_ID_EXTRA, myPoll.getId());
				startActivity(intent);
				break;
			case 1:
				intent = new Intent(this, VoteOnPollActivity.class);
				Poll participatingPoll = (Poll) participatingPollsAdapter.getItem(info.position);
				intent.putExtra(VoteOnPollActivity.POLL_ID_EXTRA, participatingPoll.getId());
				startActivity(intent);
				break;
			case 2:
				intent = new Intent(this, VoteOnPollActivity.class);
				Poll publicPoll = (Poll) publicPollsAdapter.getItem(info.position);
				intent.putExtra(VoteOnPollActivity.POLL_ID_EXTRA, publicPoll.getId());
				startActivity(intent);
				break;
			}
			return true;
		}
		return false;
	}
	
	public void onTabChanged(String tabId) {
		// TODO Auto-generated method stub
		if(initialized) {
			if(tabId.equals(MYPOLLS_TAB_TAG)) {
				PollService pollService = DefaultServiceFactory.getInstance().createPollService();
				RequestContext ctxt = RequestContext.getContext();
				Log.d("tag", ctxt.getUsername());
				try {
					myPollsList.clear();
					List<Poll> pollList = pollService.findMyPolls(ctxt, new Date(), new Date());
					myPollsList.addAll(sortAndFilterPollsByEndDate(pollList, getMinDate()));
					myPollsAdapter.notifyDataSetChanged();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			else if(tabId.equals(PARTICIPATINGPOLLS_TAB_TAG)) {
				PollService pollService = DefaultServiceFactory.getInstance().createPollService();
				RequestContext ctxt = RequestContext.getContext();
				Log.d("tag", ctxt.getUsername());
				try {
					participatingPollsList.clear();
					List<Poll> pollList = pollService.findParticipantPolls(ctxt, new Date(), new Date());
					participatingPollsList.addAll(sortAndFilterPollsByEndDate(pollList, getMinDate()));
					participatingPollsAdapter.notifyDataSetChanged();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			else if(tabId.equals(PUBLICPOLLS_TAB_TAG)) {
				PollService pollService = DefaultServiceFactory.getInstance().createPollService();
				RequestContext ctxt = RequestContext.getContext();
				Log.d("tag", ctxt.getUsername());
				try {
					publicPollsList.clear();
					List<Poll> pollList = pollService.findPublicPolls(ctxt, new Date(), new Date());
					publicPollsList.addAll(sortAndFilterPollsByEndDate(pollList, getMinDate()));
					publicPollsAdapter.notifyDataSetChanged();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private List<Poll> sortAndFilterPollsByEndDate (List<Poll> pollList, Date minDate) {
		List<Poll> newPollList = new ArrayList<Poll>();
		for (Poll poll : pollList) {
			if (poll.getEndDate().after(minDate))
				newPollList.add(poll);
		}
		Collections.sort(newPollList, new Comparator<Poll>() {
			public int compare(Poll lhs, Poll rhs) {
				return lhs.getEndDate().compareTo(rhs.getEndDate());
			}
		});
		return newPollList;
	}
	
	private Date getMinDate() {
		Calendar c = Calendar.getInstance();
		c.add(Calendar.DAY_OF_WEEK, -7);
		return c.getTime();
	}
	
	private void showToast(String message) {
		Log.d("hello", "made to toast.maketext");
		Toast.makeText(this, message, Toast.LENGTH_SHORT);
	}
}
